package com.hzlx.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class TokenService {
    @Value("${security.key}")
    String key = "successisnotfinalfailureisnotfatalitisthecouragetocontinuethatcounts";
    @Value("${expire.date}")
    long expireDate = 864_000_000;
    public String generateToken(String name, List<String> authorities) {
        return Jwts.builder()
                .setSubject(name)                      // 用户账户
                .claim("authorities", authorities)     // 权限
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expireDate))
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
    }
    // 解析令牌
    public Claims validateToken(String token){
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build().parseClaimsJws(token)
                    .getBody();
        }catch (RuntimeException e){
            e.printStackTrace();
            return null;
        }
    }
}
